package online_exams.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器
        registry.addInterceptor(new SaInterceptor(handle -> {
                    // 所有接口都需要登录
                    StpUtil.checkLogin();
                    // 管理员路径权限验证
                    SaRouter.match("/admin/**", r -> {
                        // 检查是否为管理员角色
                        String role = (String) StpUtil.getSession().get("role");
                        if (!"admin".equals(role)) {
                            throw new RuntimeException("无权限访问");
                        }
                    });
                }))
                .addPathPatterns("/**")  // 拦截所有路径
                .excludePathPatterns(    // 排除不需要拦截的路径
                        "/tUser/login",
                        "/tUser/Userinsert",
                        "/tUser/inspectlogin"

                );
    }
}